package logic

import (
	"errors"
	"github.com/levigross/grequests"
	"os"
	"strings"
)

// DownloadFile 下载文件
func DownloadFile(fileName string, url string) error {
	//创建临时文件
	out, err := os.Create(fileName + ".tmp")
	if err != nil {
		_ = out.Close()
		return err
	}

	res, err := grequests.Get(url, &grequests.RequestOptions{
		Headers: map[string]string{
			"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Mobile Safari/537.36",
		},
	})
	if err != nil {
		_ = out.Close()
		return err
	}
	defer res.Close()
	//下载视频到临时文件
	err = res.DownloadToFile(fileName + ".tmp")
	if err != nil {
		_ = out.Close()
		return err
	}
	//关闭文件句柄
	_ = out.Close()

	//文件下载成功后改为原来的文件名
	if err = os.Rename(fileName+".tmp", fileName); err != nil {
		_ = out.Close()
		return err
	}
	//删除临时文件
	_ = os.Remove(fileName + ".tmp")
	return nil
}

// GetVideoURL 获取视频地址
func GetVideoURL(urlText string) (string, error) {
	//抖音
	if strings.Contains(urlText, "douyin") {
		return GetDouYinVideoUrl(urlText)
	}

	//bilibili
	if strings.Contains(urlText, "bilibili.com") {
		return getBilibiliVideoUrl(urlText)
	}

	//开眼
	if strings.Contains(urlText, "eyepetizer") {
		return getEyePetizerVideoUrl(urlText)
	}

	//默默
	if strings.Contains(urlText, "immomo") {
		return getMonMoVideoUrl(urlText)
	}

	//全民K歌
	if strings.Contains(urlText, "kg3.qq.com") {
		return getKg3VideoUrl(urlText)
	}

	//快手
	if strings.Contains(urlText, "immomo") {
		return getKuaiShouVideoUrl(urlText)
	}

	//皮皮虾
	if strings.Contains(urlText, "pipix") {
		return getPiPixVideoUrl(urlText)
	}

	//微博
	if strings.Contains(urlText, "weibo.com") {
		return getWeiBoVideoUrl(urlText)
	}

	//微视
	if strings.Contains(urlText, "weishi") {
		return getWeiShiVideoUrl(urlText)
	}

	//最右
	if strings.Contains(urlText, "zuiyou") {
		return getZuiYouVideo(urlText)
	}

	return "", errors.New("文件地址获取失败")
}
